package cn.lili.xiaoran.controller;

import cn.lili.modules.goods.util.Generator;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.MemberPointsHistory;
import cn.lili.modules.member.entity.enums.PointTypeEnum;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.mapper.MemberPointsHistoryMapper;
import cn.lili.modules.member.service.MemberPointsHistoryService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.search.entity.EsQuestionDetail;
import cn.lili.modules.search.entity.EsQuestionIndex;
import cn.lili.modules.search.service.EsGoodsIndexService;
import cn.lili.xiaoran.entity.*;
import cn.lili.xiaoran.entity.dtos.LiQuestionsDTO;
import cn.lili.xiaoran.entity.dtos.LiQuestionsDetailDTO;
import cn.lili.xiaoran.entity.vo.LiQuestionsDetailVo;
import cn.lili.xiaoran.entity.vo.LiQuestionsVo;
import cn.lili.xiaoran.mapper.LiQuestionsDetailMapper;
import cn.lili.xiaoran.mapper.LiQuestionsMapper;
import cn.lili.xiaoran.service.LiQuestionsDetailService;
import cn.lili.xiaoran.service.LiQuestionsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.SearchVO;
import cn.lili.common.vo.ResultMessage;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

import javax.annotation.Resource;
import javax.management.Query;

/**
 * 提问表(LiQuestionsDetail)表控制层
 *
 * @author makejava
 * @since 2022-08-14 13:52:39
 */
@RestController
@Api(tags = "liQuestionsDetail接口")
@RequestMapping("/buyer/lili/liQuestionsDetail")
@Transactional(rollbackFor = Exception.class)
public class LiQuestionsDetailController {
    /**
     * 服务对象
     */
    @Resource
    private LiQuestionsDetailService liQuestionsDetailService;

    @Resource
    private MemberPointsHistoryMapper memberPointsHistoryMapper;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberPointsHistoryService memberPointsHistoryService;

    @Resource
    private LiQuestionsMapper liQuestionsMapper;


    @Autowired
    private EsGoodsIndexService esGoodsIndexService;

    @Autowired
    private LiQuestionsDetailMapper liQuestionsDetailMapper;

    @Autowired
    private LiQuestionsService liQuestionsService;

    @GetMapping(value = "/{id}")
    @ApiOperation(value = "查看${tableInfo.description}详情")
    public ResultMessage<LiQuestionsDetail> get(@PathVariable Integer id) {

        LiQuestionsDetail liQuestionsDetail = liQuestionsDetailService.getById(id);
        return new ResultUtil<LiQuestionsDetail>().setData(liQuestionsDetail);
    }

    @GetMapping
    @ApiOperation(value = "分页获取${tableInfo.description}")
    public ResultMessage<IPage<LiQuestionsDetail>> getByPage(LiQuestionsDetailDTO page) {
        IPage<LiQuestionsDetail> data = this.liQuestionsDetailService.page(PageUtil.initPage(page), page.queryWrapper());
        return new ResultUtil<IPage<LiQuestionsDetail>>().setData(data);
    }

    @PostMapping
    @ApiOperation(value = "新增${tableInfo.description}")
    public ResultMessage<LiQuestionsDetail> save(LiQuestionsDetail liQuestionsDetail) {
        LiQuestions questions=liQuestionsMapper.selectById(liQuestionsDetail.getQuestionsId());
        if(!questions.getUserId().equals(liQuestionsDetail.getUserId())){
            liQuestionsDetail.setIsfaqirenweidu(true);
            liQuestionsDetail.setIshoutaiweidu(true);
        }else{
            liQuestionsDetail.setIshoutaiweidu(true);
        }
        questions.setIsweidu(true);
        liQuestionsMapper.updateById(questions);
        if (this.liQuestionsDetailService.save(liQuestionsDetail)) {
            new Thread(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    QueryWrapper<LiQuestions> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("id", liQuestionsDetail.getQuestionsId());
                    queryWrapper.last(" limit 1");
                    LiQuestions liQuestions = liQuestionsMapper.selectOne(queryWrapper);
                    EsQuestionIndex index = Generator.convert(liQuestions, EsQuestionIndex.class);
                    List<LiQuestionsDetailVo> details = liQuestionsDetailMapper.getDetailByQuestionId(liQuestionsDetail.getQuestionsId());
                    index.setDetails(Generator.convert(details, EsQuestionDetail.class));
                    esGoodsIndexService.updateQuestionIndex(liQuestionsDetail.getQuestionsId() + "", index);
                }
            }).start();
            QueryWrapper<MemberPointsHistory> query=new QueryWrapper<>();
            query.eq("type",2);
            query.eq("member_id",liQuestionsDetail.getUserId());
            Long count=memberPointsHistoryService.count(query);
//            MemberPointsHistory his = memberPointsHistoryMapper.getMemberPointsHistoryByType(2, Integer.parseInt(liQuestionsDetail.getUserId()+""));
//            if (his == null) {
            Member member = memberService.getById(liQuestionsDetail.getUserId());
            if (member != null && count<11) {
                Long point = 10L;
                //积分变动后的会员积分
                long currentPoint;
                //会员总获得积分
                long totalPoint = member.getTotalPoint();
                //如果增加积分
                currentPoint = member.getPoint() + point;
                //如果是增加积分 需要增加总获得积分
                totalPoint = totalPoint + point;
                member.setPoint(currentPoint);
                member.setTotalPoint(totalPoint);
                boolean result = memberService.updateById(member);
                String type = PointTypeEnum.INCREASE.name();
                MemberPointsHistory memberPointsHistory = new MemberPointsHistory();
                memberPointsHistory.setMemberId(member.getId());
                memberPointsHistory.setMemberName(member.getUsername());
                memberPointsHistory.setPointType(type);
                memberPointsHistory.setVariablePoint(point);
                memberPointsHistory.setBeforePoint(member.getPoint() - point);
                memberPointsHistory.setType(2);
                memberPointsHistory.setPoint(member.getPoint());
                memberPointsHistory.setContent("回答问题获得积分");
                memberPointsHistory.setCreateBy("系统");
                memberPointsHistory.setQuestionsId(liQuestionsDetail.getId());
                memberPointsHistoryService.save(memberPointsHistory);
//                }

//                LiQuestions liQuestions = liQuestionsMapper.queryById(liQuestionsDetail.getQuestionsId());





            }
            LiQuestions liQuestions = liQuestionsService.getById(liQuestionsDetail.getQuestionsId());
            Member tiwenmember = memberService.getById(liQuestions.getUserId());
            QueryWrapper<MemberPointsHistory> query1=new QueryWrapper<>();
            query1.eq("type",1);
            query1.eq("member_id",liQuestionsDetail.getUserId());
            Long count1=memberPointsHistoryService.count(query1);
            if(tiwenmember!=null && count1<11){
                Long point = 10L;
                //积分变动后的会员积分
                long currentPoint;
                //会员总获得积分
                long totalPoint = tiwenmember.getTotalPoint();

                if(tiwenmember!=null){
                    totalPoint = tiwenmember.getTotalPoint();
                }
                //如果增加积分
                currentPoint = tiwenmember.getPoint() + point;
                //如果是增加积分 需要增加总获得积分
                totalPoint = totalPoint + point;
                tiwenmember.setPoint(currentPoint);
                tiwenmember.setTotalPoint(totalPoint);
                memberService.updateById(tiwenmember);
                MemberPointsHistory memberPointsHistory = new MemberPointsHistory();
                String type = PointTypeEnum.INCREASE.name();
                memberPointsHistory = new MemberPointsHistory();
                memberPointsHistory.setMemberId(tiwenmember.getId());
                memberPointsHistory.setMemberName(tiwenmember.getUsername());
                memberPointsHistory.setPointType(type);
                memberPointsHistory.setVariablePoint(point);
                memberPointsHistory.setBeforePoint(tiwenmember.getPoint()-point );
                memberPointsHistory.setType(1);
                memberPointsHistory.setPoint(tiwenmember.getPoint());
                memberPointsHistory.setContent("提问获得积分");
                memberPointsHistory.setCreateBy("系统");
                memberPointsHistory.setQuestionsId(liQuestions.getId());
                memberPointsHistoryService.save(memberPointsHistory);
            }

            return new ResultUtil<LiQuestionsDetail>().setData(liQuestionsDetail);
        }
        return new ResultUtil<LiQuestionsDetail>().setErrorMsg("未知异常，请稍后重试");
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "更新${entity.description}")
    public ResultMessage<LiQuestionsDetail> update(@PathVariable String id, LiQuestionsDetail liQuestionsDetail) {
        if (this.liQuestionsDetailService.updateById(liQuestionsDetail)) {
            return new ResultUtil<LiQuestionsDetail>().setData(liQuestionsDetail);
        }
        return new ResultUtil<LiQuestionsDetail>().setErrorMsg("未知异常，请稍后重试");
    }

    @DeleteMapping(value = "/{ids}")
    @ApiOperation(value = "删除提问表")
    public ResultMessage<Object> delAllByIds(@PathVariable List ids) {

        liQuestionsDetailService.removeByIds(ids);
        ids.forEach(id->{
            MemberPointsHistory his = memberPointsHistoryMapper.getMemberPointsHistoryByType(2, Integer.parseInt(id.toString()));
            if(his!=null){
                memberPointsHistoryMapper.deleteById(his.getId());
            }
        });

        return ResultUtil.success("成功删除");
    }

    @GetMapping("/wodehuida")
    @ApiOperation(value = "我的回答")
    public ResultMessage<IPage<LiQuestionsDetail>> getwodehuida(LiQuestionsDetailDTO page) {
        IPage<LiQuestionsDetail> data = this.liQuestionsDetailService.page(PageUtil.initPage(page), page.queryWrapper());
        List<LiQuestionsDetail> list = data.getRecords();
        List<Integer> ids = new ArrayList<>();
        list.forEach(item -> {
            ids.add(item.getQuestionsId());
        });
        QueryWrapper<LiQuestions> query = new QueryWrapper<>();
        List<LiQuestions> qs = new ArrayList<>();
        if (ids.size() > 0) {
            query.in("id", ids);
            query.eq("delete_flag", 0);
            qs = liQuestionsMapper.selectList(query);
        }
        Map<Integer, LiQuestions> qsmap = new HashMap<>();
        qs.forEach(item -> {
            qsmap.put(item.getId(), item);
        });
        list.forEach(item -> {
            if (qsmap.containsKey(item.getQuestionsId())) {
                item.setLiQuestions(qsmap.get(item.getQuestionsId()));
            }
        });
        list.stream().filter(new Predicate<LiQuestionsDetail>() {
            @Override
            public boolean test(LiQuestionsDetail liQuestionsDetail) {
                return liQuestionsDetail.getLiQuestions()!=null;
            }
        });
        data.setRecords(list);
        return new ResultUtil<IPage<LiQuestionsDetail>>().setData(data);
    }

    @GetMapping("/wodetiwenhuidashu/{userId}")
    @ApiOperation(value = "我的回答")
    public ResultMessage<Map<String,Object>> wodetiwenhuidashu(@PathVariable String userId) {
        ResultMessage reslut= new ResultMessage();
        Map<String,Object> map=new HashMap<>();
        Long count=liQuestionsDetailMapper.selmycount(userId);
        map.put("count",count);
        reslut.setResult(map);
        return reslut;
    }
}

